/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bonbhel.oracle.auctionApp.resource;

import com.bonbhel.oracle.auctionApp.Item;
import java.util.Collection;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import com.bonbhel.oracle.auctionApp.Bid;
import java.util.List;
import com.bonbhel.oracle.auctionApp.Seller;
import com.bonbhel.oracle.auctionApp.converter.ItemConverter;
import javax.ejb.Stateless;

/**
 *
 * @author bonbhejf
 */

@Stateless
public class ItemResource {
    @javax.ejb.EJB
    private SellerResourceSub sellerResourceSub;
    @javax.ejb.EJB
    private BidsResourceSub bidsResourceSub;
    @Context
    protected UriInfo uriInfo;
    protected EntityManager em;
    protected Long id;
  
    /** Creates a new instance of ItemResource */
    public ItemResource() {
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    /**
     * Get method for retrieving an instance of Item identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of ItemConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public ItemConverter get(@QueryParam("expandLevel")
                             @DefaultValue("1")
    int expandLevel) {
        return new ItemConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
    }

    /**
     * Put method for updating an instance of Item identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an ItemConverter entity that is deserialized from a XML stream
     */
    @PUT
    @Consumes({"application/xml", "application/json"})
    public void put(ItemConverter data) {
        updateEntity(getEntity(), data.resolveEntity(em));
    }

    /**
     * Delete method for deleting an instance of Item identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        deleteEntity(getEntity());
    }

    /**
     * Returns an instance of Item identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of Item
     */
    protected Item getEntity() {
        try {
            return (Item) em.createQuery("SELECT e FROM Item e where e.id = :id").setParameter("id", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    private Item updateEntity(Item entity, Item newEntity) {
        List<Bid> bids = entity.getBids();
        List<Bid> bidsNew = newEntity.getBids();
        Seller seller = entity.getSeller();
        Seller sellerNew = newEntity.getSeller();
        entity = em.merge(newEntity);
        for (Bid value : bids) {
            if (!bidsNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from bids"));
            }
        }
        for (Bid value : bidsNew) {
            if (!bids.contains(value)) {
                Item oldEntity = value.getItem();
                value.setItem(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getBids().remove(value);
                }
            }
        }
        if (seller != null && !seller.equals(sellerNew)) {
            seller.getItems().remove(entity);
        }
        if (sellerNew != null && !sellerNew.equals(seller)) {
            sellerNew.getItems().add(entity);
        }
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    private void deleteEntity(Item entity) {
        if (!entity.getBids().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because bids is not empty."));
        }
        Seller seller = entity.getSeller();
        if (seller != null) {
            seller.getItems().remove(entity);
        }
        em.remove(entity);
    }

    /**
     * Returns a dynamic instance of BidsResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of BidsResource
     */
    @Path("bids/")
    public BidsResource getBidsResource() {
        bidsResourceSub.setParent(getEntity());
        return bidsResourceSub;
    }

    /**
     * Returns a dynamic instance of SellerResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of SellerResource
     */
    @Path("seller/")
    public SellerResource getSellerResource() {
        sellerResourceSub.setParent(getEntity());
        return sellerResourceSub;
    }

    @Stateless(name = "ItemResource.BidsResourceSub")
    public static class BidsResourceSub extends BidsResource {

        private Item parent;

        public void setParent(Item parent) {
            this.parent = parent;
        }

        @Override
        protected Collection<Bid> getEntities(int start, int max, String query) {
            Collection<Bid> result = new java.util.ArrayList<Bid>();
            int index = 0;
            for (Bid e : parent.getBids()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    @Stateless(name = "ItemResource.SellerResourceSub")
    public static class SellerResourceSub extends SellerResource {

        private Item parent;

        public void setParent(Item parent) {
            this.parent = parent;
        }

        @Override
        protected Seller getEntity() {
            Seller entity = parent.getSeller();
            if (entity == null) {
                throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
            }
            return entity;
        }
    }
}
